package com.department.mydepartment.service;


import com.department.mydepartment.entities.Article;
import com.department.mydepartment.entities.User;
import com.department.mydepartment.repository.UserRepository;
import com.department.mydepartment.util.ShowData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.sql.Timestamp;
import java.util.List;

@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    @Autowired
    ShowData showData;

    /**
     * 登录
     * @param userId
     * @param password
     * @return
     */
    public String login(String userId, String password){
        if ("admin".equals(userId) && "admin9999".equals(password)) {
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            User user = new User(userId, password, timestamp, timestamp);
            userRepository.save(user);
            return showData.showData(true,"登录成功");
        }
        return showData.showData(false, "用户名或密码错误");
    }

    /**
     * 查找
     * @return
     */

    public String findAllUser() {
        List<User> allUser = userRepository.findAll();
        return showData.showData(true, allUser.toString());
    }

    public String findByUserId(String userId) {
        User byUserId = userRepository.findByUserId(userId);
        return showData.showData(true, byUserId.toString());
    }

    /**
     * 更改密码
     * @param userId
     * @return
     */
    public String editByUserId(String userId, String passwordConfirmed) {
        User byUserId = userRepository.findByUserId(userId);
        if (byUserId != null) {
            byUserId.setPassword(passwordConfirmed);
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            byUserId.setUpdateTime(timestamp);
            userRepository.save(byUserId);
            return showData.showData(true, "修改成功");
        }
        return showData.showData(false, "用户不存在");
    }

    /**
     * 删除
     * @param userId
     * @return
     */
    @Transactional
    public String deleteByUserId(String userId) {
        User byUserId = userRepository.findByUserId(userId);
        if (byUserId != null) {
            userRepository.deleteByUserId(userId);
            List<User> allUser = userRepository.findAll();
            return showData.showData(true, allUser.toString());
        }
        return showData.showData(false, "用户不存在");
    }
}
